package org.jash.shop2202.utils

import android.content.Context
import android.view.View
import android.widget.CheckBox
import android.widget.ImageView
import androidx.coordinatorlayout.widget.CoordinatorLayout
import androidx.databinding.BindingAdapter
import androidx.databinding.InverseBindingAdapter
import androidx.databinding.InverseBindingListener
import com.bumptech.glide.Glide
import com.bumptech.glide.load.resource.bitmap.CircleCrop
import com.bumptech.glide.load.resource.bitmap.RoundedCorners
import com.google.android.material.behavior.SwipeDismissBehavior
import com.google.android.material.checkbox.MaterialCheckBox
import com.youth.banner.Banner
import com.youth.banner.loader.ImageLoader

@BindingAdapter(value = ["image_url", "radius", "circle"], requireAll = false)
fun loadImage(image:ImageView, url:String?, radius:Int = 0, circle:Boolean = false) {
    Glide.with(image)
        .load(url)
        .apply {
            if (radius != 0) {
                transform(RoundedCorners(radius))
            }
            if (circle) {
                transform(CircleCrop())
            }
        }
        .into(image)
}
@BindingAdapter("images")
fun loadBannerImages(banner: Banner, images:List<String>?) {
    images?.let {
        banner.setImageLoader(object : ImageLoader() {
            override fun displayImage(context: Context?, path: Any?, imageView: ImageView?) {
                imageView?.let {
                    Glide.with(it)
                        .load(path)
                        .into(it)
                }
            }
        }).update(it)
    }
}
@BindingAdapter("onSwipe")
fun setOnSwipe(view:View, swipe:() -> Unit) {
    (view.layoutParams as? CoordinatorLayout.LayoutParams)?.let {
        val behavior = SwipeDismissBehavior<View>()
        behavior.listener = object : SwipeDismissBehavior.OnDismissListener {
            override fun onDismiss(view: View?) {
                view?.alpha = 1f
                swipe()
            }

            override fun onDragStateChanged(state: Int) {

            }
        }
        it.behavior = behavior
    }
}

@InverseBindingAdapter(attribute = "checkedState")
fun getCheckedState(checkBox: MaterialCheckBox) = checkBox.checkedState

@BindingAdapter("checkedStateAttrChanged")
fun checkedListener(checkBox: MaterialCheckBox, event: InverseBindingListener) {
    checkBox.addOnCheckedStateChangedListener { _, _ -> event.onChange() }
}